package com.hst.capacity.domain.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hst.capacity.domain.model.entity.franchisee.AgentEntity;
import com.hst.capacity.domain.model.request.agent.AgentSaveParam;
import com.hst.capacity.domain.service.AgentService;
import com.hst.capacity.infra.persistence.jpa.agent.AgentInforRepository;
import com.hst.capacity.infra.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AgentServiceImpl implements AgentService {

    @Autowired
    private AgentInforRepository agentInforRepository;

    /**
     * 保存/更新代理商信息
     * @param param
     * @return
     */
    @Override
    public AgentEntity save(AgentSaveParam param) {
        AgentEntity result = null;
        AgentEntity entity = null;
        if (StringUtil.isNotBlank(param.getIdAgent())) {
            entity = agentInforRepository.findByIdAgent(param.getIdAgent());
            entity.setStatus(param.getStatus());
            entity.setAgentName(param.getAgentName());
            entity.setAgentAddress(param.getAgentAddress());
            entity.setAgentTel(param.getAgentTel());
            entity.setAgentAdmin(param.getAgentAdmin());
        } else {
            entity = newAgentEntity(param);
            if (StrUtil.isEmpty(param.getIdAgent()))
                entity.setIdAgent(StringUtil.generateUuid());
        }
        result = agentInforRepository.save(entity);
        return result;
    };

    /**
     * 检查电话是否已经注册
     * @param param
     * @return
     * */
    @Override
    public boolean checkTel(AgentSaveParam param) {
        AgentEntity entity = agentInforRepository.findByAgentTel(param.getAgentTel());
        boolean result = (entity != null);
        if (StringUtil.isNotBlank(param.getIdAgent()) && result)
            result = !param.getIdAgent().equals(entity.getIdAgent());
        return result;
    };

    private AgentEntity newAgentEntity(AgentSaveParam param){
        AgentEntity agentEntity = new AgentEntity();
        agentEntity.setIdAgent(param.getIdAgent());
        agentEntity.setIdFranchisee(param.getIdFranchisee());
        agentEntity.setAgentName(param.getAgentName());
        agentEntity.setStatus(param.getStatus());
        agentEntity.setAgentAddress(param.getAgentAddress());
        agentEntity.setAgentTel(param.getAgentTel());
        agentEntity.setAgentAdmin(param.getAgentAdmin());
        agentEntity.setDriverNum(0);
        agentEntity.setFleetNum(0);
//        agentInforEntity.setIdUser();
//        agentInforEntity.setQrCode();
//        agentInforEntity.setCreateBy();
//        agentInforEntity.setCreateTime();
//        agentInforEntity.setUpdateTime();
        return agentEntity;
    }

}
